package dao

import (
	"github.com/jinzhu/gorm"
	"pojo/model"
	"pojo/form"
	"bytes"
)

// goods数据库访问对象
type GoodsDao struct {
	db *gorm.DB
}

// 构建GoodsDao对象
func NewGoodsDao(db *gorm.DB) *GoodsDao {
	return &GoodsDao{
		db: db,
	}
}

// 保存商品信息
func (this *GoodsDao) InsertGoods(goods *model.Goods) (affected int64, err error) {
	result := this.db.Save(goods)
	return result.RowsAffected, result.Error
}

// 删除商品信息
func (this *GoodsDao) DeleteGoods(id uint64) (affected int64, err error) {

	result := this.db.Where("id = ?", id).Delete(model.Goods{})

	return result.RowsAffected, result.Error
}

// 查询单个商品信息
func (this *GoodsDao) FindGoods(id uint64) (*model.Goods, error) {

	goods := &model.Goods{}

	result := this.db.Where("id = ?", id).Find(goods)

	return goods, result.Error
}

// 查询商品列表
func (this *GoodsDao) ListGoods(goods *form.GoodsForm) ([]model.Goods, error) {
	goodsList := make([]model.Goods, 0)
	result := this.db.Where("name Like ?", "%"+goods.Name+"%").Find(&goodsList)
	return goodsList, result.Error
}

// 修改商品信息
func (this *GoodsDao) UpdateGoods(goods *model.Goods) (affected int64, err error) {

	result := this.db.Save(goods)

	return result.RowsAffected, result.Error
}

// 根据条件统计商品条数
func (this *GoodsDao) Count(queryForm *form.GoodsPageQueryForm) (uint64, error) {

	var total uint64

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(queryForm.Name) > 0 {
		buf.WriteString(" and name like ? ")
		params = append(params, queryForm.Name)
	}

	if queryForm.Cid > 0 {
		buf.WriteString(" and cid = ? ")
		params = append(params, queryForm.Cid)
	}

	rs := this.db.Model(model.Goods{}).Where(buf.String(), params...).Count(&total)

	return total, rs.Error
}

// 根据条件分页查询商品信息
func (this *GoodsDao) List(queryForm *form.GoodsPageQueryForm) ([]*model.Goods, error) {

	goods := make([] *model.Goods, 0)

	offset := (queryForm.Page - 1) * queryForm.Limit

	params := make([]interface{}, 0)

	buf := new(bytes.Buffer)
	buf.WriteString(" 1 = 1 ")

	if len(queryForm.Name) > 0 {
		buf.WriteString(" and name like ? ")
		params = append(params, queryForm.Name)
	}

	if queryForm.Cid > 0 {
		buf.WriteString(" and cid = ? ")
		params = append(params, queryForm.Cid)
	}

	rs := this.db.Where(buf.String(), params...).Order("created_at").Offset(offset).Limit(queryForm.Limit).Find(&goods)

	return goods, rs.Error
}
